﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Data;
using System.Collections.Specialized;

namespace TXTMonitor
{
    public class Process : FileMonitor.Provider.FileMonitor.FileMonitorBase
    {
       

        public override void ProcessChanged(FileSystemEventArgs e)
        {
        }


        public override void ProcessCreated(FileSystemEventArgs e)
        {
             try
            {
                string filename = e.Name;
                string filterPlantCode = this.AllConfig["FilterPlantCode"];
                string plantCode = this.GetPlantCodeFromFileName(e.Name);
                
                if (string.IsNullOrEmpty(filterPlantCode))
                {
                    ProcessFile(filename, e.FullPath);
                }
                else
                {
                    string[] filterPlants = filterPlantCode.Split(",".ToCharArray());
                    if (filterPlants != null)
                    {
                        if (filterPlants.Length == 0)
                        {
                            ProcessFile(filename, e.FullPath);
                        }
                        else
                        {
                            if (!filterPlantCode.Contains(plantCode))
                            {
                                ProcessFile(filename, e.FullPath);
                            }
                        }

                    }
                    else
                    {
                        ProcessFile(filename, e.FullPath);
                    }
                }

            }


            catch (Exception ex)
            {
                 throw new Exception(ex.Message);
            }
        }

        private void ProcessFile(string filename, string filePath)
        {
            #region
            //   string filePath = e.FullPath;
            //DataTable _dtScheml = FileUtility.Utility.GetDataTableNoData(exchangeDB, this.AllConfig["TargetTable"]);
            // #region 获取PlantCode
            ////string plantCodeIndex = string.IsNullOrEmpty(this.AllConfig["PlantCodeIndex"]) ? "0" : this.AllConfig["PlantCodeIndex"];
            ////string plantCodeLength = string.IsNullOrEmpty(this.AllConfig["PlantCodeLength"]) ? "4" : this.AllConfig["PlantCodeLength"];
            ////string plantCode = filename.Substring(Int32.Parse(plantCodeIndex), Int32.Parse(plantCodeLength));
            //string plantCode = this.GetPlantCodeFromFileName(filename);
            // #endregion

         
            
            //string _Prifix, _fileCountsExt;
            //int totalFiles, currentFile;
            //if (filename.IndexOf("(") > 0)
            //{
            //    _Prifix = filename.Substring(0, filename.LastIndexOf("("));
            //    _fileCountsExt = filename.Substring(filename.LastIndexOf("(") + 1, filename.LastIndexOf(")") - filename.LastIndexOf("(") - 1);
            //    totalFiles = Int32.Parse(_fileCountsExt.Substring(0, _fileCountsExt.IndexOf("_")));
            //    currentFile = Int32.Parse((_fileCountsExt.Substring(_fileCountsExt.IndexOf("_"), _fileCountsExt.Length - _fileCountsExt.IndexOf("_"))).TrimStart("_".ToCharArray()));
            //}
            //else
            //{
            //    _Prifix = filename.Substring(0, filename.LastIndexOf("."));
            //    totalFiles = 1;
            //    currentFile = 1;
            //}
            //bool IsNew = true;

            //Guid batchId = FileUtility.Utility.GetBatchID("Forecast", exchangeDB, "TransferLogT", _Prifix, out IsNew);
            //if (IsNew)
            //{
            //    currentFile = 0;
            //    FileUtility.Utility.AddNewFileLog(targetExchangDB, batchId, this.AllConfig["DataType"], this.AllConfig["MonitorPath"], _Prifix, totalFiles, currentFile, 0, -1,plantCode);

            //}
            //try
            //{

            //    // System.Windows.Forms.MessageBox.Show(filePath);
            //    DataTable dtContent = FileUtility.Utility.ReadFileContentToDataTable(filePath, _dtScheml, batchId, splitChar);
            //    string _connString = targetExchangDB.CreateConnection().ConnectionString;
            //    System.Data.SqlClient.SqlBulkCopy sqlBulkCopy = new System.Data.SqlClient.SqlBulkCopy(_connString, System.Data.SqlClient.SqlBulkCopyOptions.UseInternalTransaction);
            //    sqlBulkCopy.DestinationTableName = this.AllConfig["TargetTable"];
              
            //    sqlBulkCopy.BulkCopyTimeout = 360;
            //    DataTable dtSchema = this.GetSchema(this.AllConfig["TargetTable"], _connString);
            //    CheckData(dtContent, dtSchema);
            //    if (!string.IsNullOrEmpty(this.AllConfig["DataFilter"]))
            //    {
            //       sqlBulkCopy.WriteToServer(dtContent.Select(this.AllConfig["DataFilter"]));
            //       FileUtility.Utility.AddFileCount(targetExchangDB, batchId, dtContent.Select(this.AllConfig["DataFilter"]).Length);
            //    }
            //    else
            //    {
            //       sqlBulkCopy.WriteToServer(dtContent);
            //       FileUtility.Utility.AddFileCount(targetExchangDB, batchId, dtContent.Rows.Count);
            //     }
            //}
            //catch (Exception ex)
            //{
            //    FileUtility.Utility.SaveException(targetExchangDB, batchId, ex.Message, filename);
            //    throw new Exception(ex.Message);
            //}
            #endregion
            string plantCode = GetPlantCodeFromFileName(filename);
            DataTable dtConfig = FileUtility.Utility.ReadProcessConfigByPlant(this.exchangeDB, plantCode, this.AllConfig["DataType"]);
            string splitArr = "";
            if (base.splitFlag == FileMonitor.Provider.FileMonitor.SplitFlag.LENGTH)
            {
                string processProviderType = System.Configuration.ConfigurationManager.AppSettings["ProcessProviderType"];
                if (processProviderType == "AppConfig")
                {
                    splitArr = System.Configuration.ConfigurationManager.AppSettings[this.AllConfig["SplitArr"]];
                }
                else
                    splitArr = this.AllConfig["SplitArr"];
            }
                
            #region Defaut Process

            if (dtConfig.Rows.Count == 0)
            {
                string targetTable = this.AllConfig["TargetTable"];
                string splitChar = this.AllConfig["SplitChar"];
                string DataType = this.AllConfig["DataType"];
                string MonitorPath = this.AllConfig["MonitorPath"];
                string DataFilter = this.AllConfig["DataFilter"];
                string  DBConnString = this.exchangeDB.CreateConnection().ConnectionString;
                DBProcess(plantCode, filename, filePath, DBConnString, targetTable, splitChar, DataType, MonitorPath, DataFilter, splitArr);
            }
            #endregion
            foreach (DataRow dr in dtConfig.Rows)
            {
                string proType = dr["ProcessType"].ToString();
                #region FTP Process
                if (proType.ToUpper() == "FTP")
                {
                    //  ftpPath,   ftpUserName,   ftpPassword,  iPort
                    string ftpPath = dr["FTPPath"].ToString();
                    string ftpUserName = dr["FTPUserName"].ToString();
                    string ftpPassword = dr["FTPPassword"].ToString();
                    string ftpPort = dr["FTPPort"].ToString();
                    string ftpFolderPath = dr["FTPFolderPath"].ToString();
                    FTPProcess(plantCode, filename, filePath, ftpPath, ftpUserName, ftpPassword, ftpPort, ftpFolderPath);

                }
                #endregion

                #region ExchangeDB Process
                if (proType.ToUpper() == "EXCHANGEDB")
                {
                    string targetTable = this.AllConfig["TargetTable"];
                    string splitChar = this.AllConfig["SplitChar"];
                    string DataType = this.AllConfig["DataType"];
                    string MonitorPath = this.AllConfig["MonitorPath"];
                    string DataFilter = this.AllConfig["DataFilter"];
                 
                    string DBConnString = dr["DBConnString"].ToString();
                    if (string.IsNullOrEmpty(DBConnString))
                    {
                        DBConnString = this.exchangeDB.CreateConnection().ConnectionString;
                    }
                    DBProcess(plantCode, filename, filePath, DBConnString, targetTable, splitChar, DataType, MonitorPath, DataFilter, splitArr);
                }
                #endregion
            }
        }

         
        #region Private Method
        private void DBProcess(string plantCode, string filename, string filePath, string DBConnString, string targetTable, string splitChar, string DataType, string MonitorPath, string DataFilter,string SplitArr)
        {
            NameValueCollection nvConfig = new NameValueCollection();
            nvConfig.Add("DBConnString", DBConnString);
            nvConfig.Add("TargetTable", targetTable);
            nvConfig.Add("SplitChar", splitChar);
            nvConfig.Add("DataType", DataType);
            nvConfig.Add("MonitorPath", MonitorPath);
            nvConfig.Add("DataFilter", DataFilter);
            nvConfig.Add("SplitArr", SplitArr);

            ProcessFileBase process = ProcessFactory.CreateProcess(ProcessType.ExChangeDB);
            process.Initialize(ProcessType.ExChangeDB, nvConfig);
            try
            {
                process.ProcessFile(plantCode, filename, filePath);
            }
            catch (Exception ex)
            {
                FileUtility.Log.Log.getInstance().WriteToLog(ex.Message, this.AllConfig["LogPath"]);
                throw new Exception(ex.Message);
            }
        }
        private void FTPProcess(string plantCode, string filename, string filePath, string ftpPath, string ftpUserName, string ftpPassword, string ftpPort, string ftpFolderPath)
        {
            NameValueCollection nvConfig = new NameValueCollection();
            nvConfig.Add("FTPPath", ftpPath);
            nvConfig.Add("FTPUserName", ftpUserName);
            nvConfig.Add("FTPPassword", ftpPassword);
            nvConfig.Add("FTPPort", ftpPort);
            nvConfig.Add("FTPFolderPath", ftpFolderPath);
            ProcessFileBase process = ProcessFactory.CreateProcess(ProcessType.FTP);
            process.Initialize(ProcessType.ExChangeDB, nvConfig);
            try
            {
                process.ProcessFile(plantCode, filename, filePath);
            }
            catch (Exception ex)
            {
                FileUtility.Log.Log.getInstance().WriteToLog(ex.Message, this.AllConfig["LogPath"]);
            }
          
        }
        #endregion

        public override void ProcessDeleted(FileSystemEventArgs e)
        {
        }


        #region Utility Method

        private string GetPlantCodeFromFileName(string FileName)
        {
            string plantCodeIndex = string.IsNullOrEmpty(this.AllConfig["PlantCodeIndex"]) ? "0" : this.AllConfig["PlantCodeIndex"];
            string plantCodeLength = string.IsNullOrEmpty(this.AllConfig["PlantCodeLength"]) ? "4" : this.AllConfig["PlantCodeLength"];
            string plantCode = FileName.Substring(Int32.Parse(plantCodeIndex), Int32.Parse(plantCodeLength));
            return plantCode;
        }

        #endregion

        #region Debug Data
        private List<string> CheckData(DataTable dtContent, DataTable dtSchema)
        {
            List<string> listErrCells = new List<string>();
            for (int i = 0; i < dtContent.Rows.Count; i++)
            {
                for (int j = 1; j < dtContent.Columns.Count; j++)
                {
                    int len = Int32.Parse(dtSchema.Rows[j][1].ToString());
                    if (len != -1)
                    {
                        if (dtContent.Rows[i][j].ToString().Length > len)
                        {
                            listErrCells.Add(i + "," + j);
                        }
                    }
                }
            }
            return listErrCells;
        }

        private DataTable GetSchema(string dtName, string connStr)
        {
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connStr);
            conn.Open();
            string cmdtext = string.Format("select c.name,c.length from syscolumns c,systypes t,sysobjects o where t.xusertype=c.xtype and o.id=c.id and o.name='{0}' order by c.colid",dtName);
            DataTable dtSchema = new DataTable();
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(cmdtext, conn);
            System.Data.SqlClient.SqlDataAdapter dap = new System.Data.SqlClient.SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            dap.Fill(ds);
            dtSchema = ds.Tables[0];
            conn.Close();
            return dtSchema;
        }
        #endregion
    }
}
